import * as fs from 'fs';
import * as path from 'path';

export class Logger {
  private static instance: Logger;
  private logFilePath: string;

  private constructor() {
    // Create logs directory if it doesn't exist
    const logsDir = path.join(__dirname, '../../logs');
    if (!fs.existsSync(logsDir)) {
      fs.mkdirSync(logsDir, { recursive: true });
    }
    
    // Set log file path
    this.logFilePath = path.join(logsDir, `log-${Logger.getTimestamp().replace(/\:/g,"-")}.log`);
    
    // Clear log file on startup
    fs.writeFileSync(this.logFilePath, '');
  }

  private static getTimestamp(): string {
    const now = new Date();
    return now.toISOString();
  }

  private static getTimestampOnlyTime(): string {
    const now = new Date();
    return now.toLocaleTimeString().replace(/\:/g,`-`);
  }

  public static getInstance(): Logger {
    if (!Logger.instance) {
      Logger.instance = new Logger();
    }
    return Logger.instance;
  }

  public log(message: string, component: string = 'General'): void {
    const timestamp = Logger.getTimestampOnlyTime();
    const logMessage = `[${timestamp}] [${component}] ${message}\n`;
    
    // Write to file
    fs.appendFileSync(this.logFilePath, logMessage);
    
    // Also write to console for immediate feedback
    console.log(`[${component}] ${message}`);
  }

  public warn(message: string, component: string = 'General'): void {
    const timestamp = Logger.getTimestampOnlyTime();
    const logMessage = `[${timestamp}] [WARN] [${component}] ${message}\n`;
    
    // Write to file
    fs.appendFileSync(this.logFilePath, logMessage);
    
    // Also write to console for immediate feedback
    console.warn(`[${component}] ${message}`);
  }

  public error(message: string, component: string = 'General'): void {
    const timestamp = Logger.getTimestampOnlyTime();
    const logMessage = `[${timestamp}] [ERROR] [${component}] ${message}\n`;
    
    // Write to file
    fs.appendFileSync(this.logFilePath, logMessage);
    
    // Also write to console for immediate feedback
    console.error(`[${component}] ${message}`);
  }
}